BEGIN WORK;
/*
Insertar un punto en la tabla point.
*/
DROP FUNCTION IF EXISTS insertPoint(varchar);
CREATE OR REPLACE FUNCTION insertPoint(vpoint varchar)
  RETURNS integer AS
$BODY$
DECLARE  
   id integer;
BEGIN
  
  EXECUTE 'SELECT nextval(''geometric_domains.feature_id_sequence'')' INTO id;
  LOCK TABLE geometric_domains.point;
  EXECUTE 'INSERT INTO geometric_domains.point(fe_id, po_geom) VALUES (' || id || ', ''' ||  vpoint || ''')';
  
  RETURN id;
END;
$BODY$
  LANGUAGE plpgsql VOLATILE;


  /*
Insertar un segmento de l�nea en la tabla line_segment.
*/
DROP FUNCTION IF EXISTS insertLineSegment(beginNode integer, endNode integer);
CREATE OR REPLACE FUNCTION insertLineSegment(beginNode integer, endNode integer)
  RETURNS integer AS
$BODY$
DECLARE  
   id integer;
BEGIN  
  EXECUTE 'SELECT nextval(''geometric_domains.feature_id_sequence'')' INTO id;
  LOCK TABLE geometric_domains.point;
  EXECUTE 'INSERT INTO geometric_domains.line_segment(
            fe_id, ls_begin_node, ls_end_node)
            VALUES (' || id || ', ' || beginNode || ', ' || endNode ||')';
  
  RETURN id;
END;
$BODY$
  LANGUAGE plpgsql VOLATILE;

DROP FUNCTION IF EXISTS deleteFeature(int, int);
CREATE OR REPLACE FUNCTION deleteFeature(gd_id int, fe_id int)
  RETURNS void AS
$BODY$
DECLARE  
   id integer;
BEGIN  
  EXECUTE 'DELETE FROM geometric_domains.geometric_domain_point        WHERE fe_id = ' || fe_id || ' AND gd_id = ' || gd_id;
  EXECUTE 'DELETE FROM geometric_domains.geometric_domain_line_segment WHERE fe_id = ' || fe_id || ' AND gd_id = ' || gd_id;   
  --delete line segment
  DELETE FROM geometric_domains.line_segment USING geometric_domains.geometric_domain_line_segment WHERE geometric_domains.line_segment.fe_id NOT IN ( SELECT DISTINCT geometric_domains.geometric_domain_line_segment.fe_id AS id FROM  geometric_domains.geometric_domain_line_segment);
  --delete point
  DELETE FROM geometric_domains.point USING geometric_domains.geometric_domain_point WHERE 
                                                           geometric_domains.point.fe_id NOT IN ( SELECT DISTINCT geometric_domains.geometric_domain_point.fe_id FROM  geometric_domains.geometric_domain_point
                                                           UNION 
                                                           SELECT DISTINCT gr_origin FROM  geometric_domains.grid 
                                                           UNION 
                                                           SELECT DISTINCT ls_begin_node FROM  geometric_domains.line_segment 
                                                           UNION 
                                                           SELECT DISTINCT ls_end_node FROM  geometric_domains.line_segment ); 
END;
$BODY$
  LANGUAGE plpgsql VOLATILE;
  
  
COMMIT;